import qs from 'qs'
import { ElMessage as Message, ElLoading as Loading } from 'element-plus'

import axios from 'axios'
import store from '@/store'

let loadingInstance

// 跨域请求，允许保存cookie
axios.defaults.withCredentials = false
// create an axios instance
const service = axios.create({
  baseURL: window.baseURL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000, // request timeout
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/json; charset=UTF-8',
  },
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    let meta = Object.assign({ showLoading: false }, config.meta)
    // showLoading 为true时 显示loading
    if (meta.showLoading) {
      loadingInstance = Loading.service({
        lock: true,
        text: '加载中...',
        spinner: 'loading',
        background: 'rgba(0, 0, 0, 0.3)',
      })
    }

    if (config.method === 'get') {
      config.params = Object.assign(config.params || {}, {
        timeVersion: Date.now(),
      })
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: 'repeat' })
      }
    }

    return config
  },
  (error) => {
    // do something with request error
    console.error(error) // for debug
    if (loadingInstance) loadingInstance.close()
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  res => res
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (res) => {
    if (loadingInstance) loadingInstance.close()
    const status = res.status
    const data = res.data

    if (status !== 200) {
      Message({
        message: '网络错误，状态码：' + status,
        type: 'error',
      })
      return Promise.reject(res)
    }

    if (!data.resultCode || data.resultCode == 200) {
      return res
    }

    let message = data.message
    switch (data.resultCode) {
      case 302: {
        window.location.href = data.data
        if (message) {
          Message({
            message,
            type: 'success',
          })
        }
        return res
      }
      case 401: {
        message = '会话过期，请重新登录'
        store.dispatch('personal/gotoLogin')
        break
      }
      case 400: {
        message = message || '请求错误'
        break
      }
      case 409: {
        message = message || '业务冲突'
        break
      }
      case 500: {
        message = message || '服务器内部错误'
        break
      }
      case 502: {
        message =
          '微服务[' + data.data.server + data.data.url + ']网关错误：' + message
        break
      }
      case 503: {
        message = '微服务[' + data.data.server + ']不可用：' + message
        break
      }
      default: {
        message = message || '未知错误'
      }
    }

    Message({
      message: message,
      type: 'error',
    })

    return Promise.reject(res)
  },
  (error) => {
    if (loadingInstance) loadingInstance.close()

    let message
    if (error.response) {
      message = error.response.data ? error.response.data.error_description : ''
      let status = error.response.status
      if (status == 400) {
        message = message || '请求参数错误'
      } else if (status == 502 || status == 503) {
        message = message || '系统升级中，请稍后再试！'
      } else if (status == 504) {
        message = message || '请求超时！'
      } else {
        message = message || '请求失败！'
      }
    } else {
      message = '服务器无响应'
    }

    Message({
      message,
      type: 'error',
    })
    return Promise.reject(error)
  }
)

export default service
